package com.frxuexi.lib_base.http

import android.util.Log
import androidx.lifecycle.MutableLiveData
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString

class WebSocketClient(val url:String) {
    val client=OkHttpClient()
    var webSocket:WebSocket?=null
    var myData=MutableLiveData<String>()
    fun start(){
        val request = Request.Builder().url(url).build()
        webSocket=client.newWebSocket(request,object :WebSocketListener(){
            override fun onOpen(webSocket: WebSocket, response: Response) {
            }
            //收到消息
            override fun onMessage(webSocket: WebSocket, text: String) {
                Log.i("lr",text)
                myData.postValue(text)
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
            }


            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            }
        })
    }

    fun sendMessage(msg:String){
        webSocket?.send(msg)
    }

    fun close(){
        webSocket?.close(1000,"关闭")
    }
}